package vn.cent.game.cardtype.server;

import java.util.List;

import vn.cent.game.cardtype.main.CardTypeGameExtension;
import com.smartfoxserver.v2.core.ISFSEvent;
import com.smartfoxserver.v2.core.SFSEventParam;
import com.smartfoxserver.v2.entities.Room;
import com.smartfoxserver.v2.entities.User;
import com.smartfoxserver.v2.exceptions.SFSException;
import com.smartfoxserver.v2.extensions.BaseServerEventHandler;

public class UserLeaveRoom extends BaseServerEventHandler {

	@Override
	public void handleServerEvent(ISFSEvent evt) throws SFSException {
		// TODO Auto-generated method stub
		// Get room that user has left
		Room room = (Room) evt.getParameter(SFSEventParam.ROOM);
		// Get left user
		User user = (User) evt.getParameter(SFSEventParam.USER);
		trace("UserLeftEventHandler");

		if(room != null && room.isGame()){
			CardTypeGameExtension gameExt = (CardTypeGameExtension) getParentExtension();

			User remainUser = FindRemainPlayer(room.getPlayersList(), user);
			if(remainUser == null)
				return;
			gameExt.send("withdraw", null, remainUser);
			//					getApi().removeRoom(room);
		}
	}

	private User FindRemainPlayer(List<User> players, User leftUser){
		for (User user : players) {
			if(user.getId() != leftUser.getId()){
				return user;
			}
		}
		return null;
	}
}
